
var ObjectID = require('mongodb').ObjectID;

var mongoBase = require('../common/mongo-base');

module.exports = {
  showPromotion: showPromotion,
  savePromotion: savePromotion,
  updatePromotion: updatePromotion,
  removePromotion: removePromotion
};


function showPromotion(req, res, next) {

  var query = {};
  var fields = {_id:1, artibodyTitle:1, mediaName:1, medialink:1, pubDate:1, key:1};
  var options = {sort:{date:1}, limit: 10};

  mongoBase.findData('home-promotion', query, fields, options)

    .then(function(data) {

      var resData = {
        promotions: data
      };
       res.render('admin/home-promotion', resData);
    })

    .catch(function(err){
      console.log(err);
    });
}

function savePromotion(req, res, next) {
  var artId = req.query.artId;

  var query = {_id: new ObjectID(artId)};
  var fields = {_id:1, artibodyTitle:1, mediaName:1, medialink:1, pubDate:1, ellipsis: 1, photo:1};
  
  mongoBase.findOneData('news-article', query, fields)

    .then(function(data) {
      var promotionData = {
        artibodyTitle: data.artibodyTitle,
        pubDate: data.pubDate,
        mediaName: data.mediaName,
        medialink: data.medialink,
        ellipsis: data.ellipsis,
        photo: data.photo,
        date: new Date(),
        key: data._id
      }
      return mongoBase.saveData('home-promotion', promotionData)
    })
    
    .then(function() {

      showPromotion(req, res, next);

    })

    .catch(function(err){
      console.log(err);
    });
}

function updatePromotion(req, res, next) {
  var artId = req.query.artId;
  var promotionId = req.query.parentId;

  var query = {_id: new ObjectID(artId)};
  var fields = {_id:1, artibodyTitle:1, mediaName:1, medialink:1, pubDate:1, ellipsis: 1, photo:1};
  
  mongoBase.findOneData('news-article', query, fields)

    .then(function(data) {
      var promotionData = {
        artibodyTitle: data.artibodyTitle,
        pubDate: data.pubDate,
        mediaName: data.mediaName,
        medialink: data.medialink,
        photo: data.photo,
        ellipsis: data.ellipsis,
        key: data._id
      }
      return mongoBase.updateData('home-promotion', {_id:new  ObjectID(promotionId)}, promotionData)
    })
    
    .then(function() {

      showPromotion(req, res, next);

    })

    .catch(function(err){
      console.log(err);
    });
}


function removePromotion(req, res, next) {
  
  var bId = req.query.bId;

  var query = {_id: new ObjectID(bId)};

  mongoBase.removeData('home-promotion', query)

    .then(function() {

      showPromotion(req, res, next);

    })

    .catch(function(err){
      console.log(err);
    });
}

